package com.trg.generaltool.util.io;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: FileWriteTest
 * Description:
 * date: 2020-09-05 11:21
 *本类主要使用到了对本地电脑文件的基本操作，读取和写出，
 * 并且是已map数据为例，输出为map格式的，读进去的时候也是map格式的
 *  {"k1":"1","k2":"2","k3":"3","k4":"4"}
 * @author tangrg
 * @since JDK 1.8
 */
public class FileWriteTest {

    public static void main(String[] args) {
        String localPath = "C:\\Users\\tangrg\\Desktop\\NCEP\\53519_pre_area1_0601_0601_2.txt";
        HashMap<String, String> map = new HashMap<>();
        map.put("k1", "1");
        map.put("k2", "2");
        map.put("k3", "3");
        map.put("k4", "4");

        fileRead(localPath);
    }

    /**
     * 通过FileWriter 将map中的数据已JSON的格式写出txt文件中
     */
    public static void fileWritve(HashMap<String, String> map,String localPath) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(new File(localPath));
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("{");

            map.forEach(
                    (k, v) -> {
                        stringBuilder.append("\""+k +"\""+ ":"+ "\""+ v +  "\""+",");
                    }
            );
            String str = stringBuilder.toString();
            str = str.substring(0,str.length()-1)+"}";
            fileWriter.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 通过FileReader读取txt文件中的内容，并读取成map格式
     */
    public static void fileRead(String localPath) {
        BufferedReader fileReader = null;
        try {
            fileReader = new BufferedReader(new FileReader(new File(localPath)));
            StringBuilder stringBuilder = new StringBuilder();
            String str;
            while ((str = fileReader.readLine()) != null) {
                System.out.println(str);
                stringBuilder.append(str);
            }
            JSONObject myJson = JSONObject.parseObject(stringBuilder.toString());
            Map m = myJson;
            System.out.println(m.get("k1"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fileReader.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}
